package netWork;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description: 回显服务器中的客户端
 * User: 王圆豪
 * Date: 2025-05-14
 * Time: 18:30
 */
public class UdpEchoClient {
    private DatagramSocket socket = null;

    private String serverIP;

    private int serverPort;

    public UdpEchoClient(String serverIP, int serverPort) throws SocketException {
        this.serverIP = serverIP;
        this.serverPort = serverPort;
        //不指定端口号，让操作系统随机分配，因为自己设置的端口号可能已经被占用。
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        System.out.println("服务器已启动！");
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("请输入你要发送的内容：");
            if (!sc.hasNext()) break;
            String request = sc.next();
            //把要发送的内容整理成数据报并且传入目的IP和目的端口
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIP),serverPort);
            //发送请求
            socket.send(requestPacket);
            //接受响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            String ret = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(ret);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
